package com.consumer.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.consumer.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@RestController
@RequestMapping("/consumer/")
@DefaultProperties(defaultFallback = "defaultFallback") // 默认熔断器降级方法注解
public class ConsumerController {

	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private DiscoveryClient discoveryClient;

	/**
	 * 直接调用my-system中的接口
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("1/{id}")
	public User getById(@PathVariable String id) {
		String url = "http://localhost:9091/user/" + id;
		return restTemplate.getForObject(url, User.class);
	}

	/**
	 * 从注册中心获取到my-system示例后，拼接接口路径调用
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("2/{id}")
	public User getById2(@PathVariable String id) {
		// 获取eureka注册中心中注册的my-system实例
		List<ServiceInstance> instanceList = discoveryClient.getInstances("my-system");
		ServiceInstance instance = instanceList.get(0);
		String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/user/" + id;
		return restTemplate.getForObject(url, User.class);
	}

	/**
	 * 利用负载均衡调用my-system服务
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("3/{id}")
	public User getById3(@PathVariable String id) {
		String url = "http://my-system/user/" + id;
		return restTemplate.getForObject(url, User.class);
	}

	/**
	 * 使用熔断器实现服务降级
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("4/{id}")
//	@HystrixCommand(fallbackMethod = "getByIdFallback") // 方法上熔断器降级方法注解
	@HystrixCommand
	public String getById4(@PathVariable String id) {
		if ("2".equals(id)) {
			throw new RuntimeException("太忙了！");
		}
		String url = "http://my-system/user/" + id;
		return restTemplate.getForObject(url, String.class);
	}

	/**
	 * getById4的降级方法
	 * 
	 * @param id
	 * @return
	 */
	public String getByIdFallback(String id) {
		System.out.println("查询用户信息失败！id：" + id);
		return "网络拥挤，请稍后再试！";
	}

	/**
	 * 整个类默认的降级方法
	 * 
	 * @return
	 */
	public String defaultFallback() {
		return "默认提示：网络拥挤，请稍后再试！";
	}
}
